package com.zzy.task;

import com.zzy.model.ScheduledCron;
import com.zzy.service.ScheduledCronService;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTaskNew implements SchedulingConfigurer {
    @Autowired
    public ScheduledCronService scheduledCronService;
    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<ScheduledCron> list = scheduledCronService.findAll();
        if(list!=null && list.size()>0){
            for (ScheduledCron scheduledCron : list) {
                taskRegistrar.addTriggerTask(
                        //1.添加任务内容(Runnable)
                        () ->
                                new Thread(){
                                    @Override
                                    public void run() {
                                        System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime() + "" + scheduledCron.getCronExpression() );
                                    }
                                }.run()
                        ,
                        //2.设置执行周期(Trigger)
                        triggerContext -> {
                            //2.1 从数据库获取执行周期
                            String cron = scheduledCron.getCronExpression();
                            //2.2 合法性校验.
                            if (StringUtils.isEmpty(cron)) {

                            }
                            //2.3 返回执行周期(Date)
                            return new CronTrigger(cron).nextExecutionTime(triggerContext);
                        }
                );
            }
        }
    }

}